package com.jdk21.core.manager;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Slf4j
@Component
public class FileManager {

    public String uploadFile(MultipartFile multipartFile) {
        String tmpdir = System.getProperties().getProperty("java.io.tmpdir");

        String fileKey = IdUtil.fastSimpleUUID();

        try {
            File tempFile = new File(tmpdir + File.separator + IdUtil.fastSimpleUUID() + multipartFile.getOriginalFilename());
            multipartFile.transferTo(tempFile);
            String fileName = fileKey + "/" + multipartFile.getOriginalFilename();
            long fileSize = tempFile.length();
            log.info("upload file, tempFile.path={} fileSize:{}", tempFile.getAbsolutePath(), tempFile.length());
            String fileType = FileTypeUtil.getType(tempFile);
            if (StringUtils.equals(fileType, "jpg") || StringUtils.equals(fileType, "png")) {
                float scale = 1.0f;
                if (fileSize > 5 * 1024 * 1024) {
                    scale = 0.4f;
                } else if (fileSize > 3 * 1024 * 1024) {
                    scale = 0.5f;
                } else if (fileSize > 2 * 1024 * 1024) {
                    scale = 0.6f;
                } else if (fileSize > 1024 * 1024) {
                    scale = 0.7f;
                } else if (fileSize > 512 * 1024) {
                    scale = 0.8f;
                }
                if (fileSize > 512 * 1024) {
                    String newFileName = tmpdir + File.separator + IdUtil.fastSimpleUUID() + multipartFile.getOriginalFilename();
                    File newFile = FileUtil.file(newFileName);
                    ImgUtil.scale(tempFile, newFile, scale);
                    boolean delete = tempFile.delete();
                    log.info("删除压缩前临时文件: {}, delete={}", tempFile.getAbsolutePath(), delete);
                    tempFile = newFile;
                    log.info("scale:{} 压缩后大小：{}", scale, tempFile.length());
                }
            }
            // 存储文件.....

            boolean delete = tempFile.delete();
            log.info("delete temp file: {}, delete={}", tempFile.getAbsolutePath(), delete);

            return fileKey;
        } catch (IOException e) {
            log.error("上传文件失败！文件名：{}", multipartFile.getOriginalFilename(), e);
        }
        return null;
    }
}
